using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using System.Web.Security;
//using ETL.Business.Handlers.ProjectCategoryHandler;
using ETL.Business.Handlers.ProjectEngineerHandler;
//using ETL.Business.Handlers.ProjectLogHandler;
using ETL.Business.Handlers.ProjectNamesHandler;
using ETL.Business.Handlers.ProjectTaskHandler;
using ETL.Business.Handlers.ProjectTimeHandler;
using ETL.Business.Handlers.SessionHandler;
using ETL.Business.Helpers;
using ETL.Business.Models;
using ETL.Common.Logging;
using ETL.Web.CustomCredential;
using ETL.Web.Filters;
using ETL.Web.Models;
using Microsoft.Practices.ServiceLocation;
using WebMatrix.WebData;
using ETL.Business.Handlers.ProjectHandlers;
using ETL.Common;
using System.Linq;

namespace ETL.Web.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class EnTimeLogController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult Index()
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return RedirectToAction("Login","Account");

            // Program Initialize
            (new ProgramInitialize()).Execute(ETLCredential.UserId, ETLCredential.UserFullName);

            // prepare date of viewmodel
            var dashboardViewModel = new DashboardViewModel();

            #region Check user role for projects loading
            // Check roles of user
            if(!Roles.IsUserInRole(Constants.RoleName.Admin))
            {
                // Get project list by userId
                var selectedProjectId = (new GetSelectedProject()).Execute(ETLCredential.UserId);

                if (selectedProjectId.HasValue)
                {
                    // Set selected project to session
                    (new SetSessionData()).Execute(Constants.SessionVars.CurrentProjectId, selectedProjectId.ToString());
                }

                // Get all projects of this user, including selected project if it's existing
                var allProjectsOfThisUser = (new GetProjectListByUser()).Execute(ETLCredential.UserId, selectedProjectId);

                // Bind to viewmodel
                dashboardViewModel.ProjectModels = allProjectsOfThisUser;
                ViewBag.IsAdminRole = false;
            }
            else
            {
                dashboardViewModel.ProjectModels = null;
                ViewBag.IsAdminRole = true;
            }
            #endregion

            #region Check user role for other engineer dropdownlist
            // Admin roles only
            if (Roles.IsUserInRole(ETLCredential.UserId, Constants.RoleName.Admin))
            {
                dashboardViewModel.ProjectUserModels = (new GetUsersToList()).Execute();
                ViewBag.IsAdminRole = true;
            }
            #endregion

            // set last activity to ViewBag
            ViewBag.LastActivity = (new GetSessionData()).Execute(Constants.SessionVars.LastActivity);
            ViewBag.TimeSpentStatus = (new GetSessionData()).Execute(Constants.SessionVars.TimeSpentStatus);

            // Get alert interval if user not log on to a task
            var alertInterval = ConfigurationManager.AppSettings["AlertInterval"].ToString();
            ViewBag.AlertInterval = alertInterval;

            return View(dashboardViewModel);
        }

        /// <summary>
        /// Activity of logon to a specific task, with task id
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public string LogOnToATask(short? taskId)
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            var curData = (new GetSessionDataModel()).Current();

            // convert to short

            short _projectId;
            short? projectId;
            if (short.TryParse(curData.ProjectId, out _projectId))
            {
                projectId = _projectId;
            }
            else projectId = null;

            short? categoryId;
            short _categoryId;
            if (short.TryParse(curData.CategoryId, out _categoryId))
            {
                categoryId = _categoryId;
            }
            else categoryId = null;

            // log on to task
            string result = (new LogOnToTask()).Execute(projectId, categoryId, taskId, ETLCredential.UserId,
                                                        ETLCredential.UserFullName);

            return result;
        }

        public string LogOnToLastTask()
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            var task = (new GetLastestProjectTask()).Execute(ETLCredential.UserId);
            var taskId = task.TaskId;
            var curData = (new GetSessionDataModel()).Current();

            // convert to short

            short _projectId;
            short? projectId;
            if (short.TryParse(curData.ProjectId, out _projectId))
            {
                projectId = _projectId;
            }
            else projectId = null;

            short? categoryId;
            short _categoryId;
            if (short.TryParse(curData.CategoryId, out _categoryId))
            {
                categoryId = _categoryId;
            }
            else categoryId = null;

            // log on to task
            string result = (new LogOnToTask()).Execute(projectId, categoryId, taskId, ETLCredential.UserId,
                                                        ETLCredential.UserFullName);

            return result;
        }

        /// <summary>
        /// function to get project detailed content
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public string GetProjectDetail(int projectId)
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            var currentProject = (new GetProjectById()).Execute(projectId);

            var result = string.Empty;
            if (currentProject != null)
            {
                result += ETLCredential.UserFullName + "#";
                //result += currentProject.ProjectLeadEnginner + "#";
                result += String.Format("{0:MMM/dd/yyyy}", currentProject.ProjectStartDate) + "#";
                result += String.Format("{0:MMM/M/yyyy}", currentProject.ProjectEndDate) + "#";
                result += currentProject.ProjectStatus + "#";
                //result += currentProject.ProjectCompleted + "#";
                //result += currentProject.ProjectSuspended + "#";
            }
            return result;

        }

        /// <summary>
        /// Return a partial view of category grid
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>

        public ActionResult GetCategory(int? projectId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;


            if (projectId.HasValue)
            {
                // Get project item
                var project = (new GetProjectById()).Execute(projectId);
                if (project == null) return null;

                //if (project.ProjectSuspended != true)
                if (!string.IsNullOrEmpty(project.ProjectStatus) && project.ProjectStatus == "SUSPENDED")
                {
                    // Log on to project
                    var curData = (new GetSessionDataModel()).Current();

                    var curUserName = ETLCredential.UserFullName;
                    var curUserId = ETLCredential.UserId;

                    // Update selected project
                    (new SetSelectedProject()).Execute(curUserId, projectId, project.ProjectName);

                    // Get category list
                    //var categoryList = (new GetProjectCategoryToList()).Execute(projectId);
                    //return PartialView("_CategoryGridPartial", categoryList);
                    return PartialView("_CategoryGridPartial", null);
                }
                else
                {
                    ViewBag.SuspendedAlert = "This project has been suspended. You cannot log onto it at the moment";
                    return PartialView("_CategoryGridPartial", null);
                }
            }
            else
            {
                ViewBag.SuspendedAlert = "Cannot find project id, please check it again";
                return PartialView("_CategoryGridPartial", null);
            }
        }

        /// <summary>
        /// Return a partial view of task grid
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult GetTask(short? projectId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;

            if ( projectId.HasValue)
            {
                var taskList = (new ShowTasks()).Execute(projectId);
                return PartialView("_TaskGridPartial", taskList);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Return a partial view of projects drop down list
        /// </summary>
        /// <param name="chkOpenProjects"></param>
        /// <param name="chkClosedProjects"></param>
        /// <returns></returns>
        public ActionResult GetProjectPartial(string chkOpenProjects, string chkClosedProjects)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;

            IEnumerable<ProjectModel> projects;
            var listProject = new List<ProjectModel>();

            if (chkClosedProjects == "LoadClosedProjects")
            {
                projects = (new GetClosedProjectList()).Execute();
            }
            else if (chkOpenProjects == "LoadOpenProjects")
            {
                projects = (new GetOpenProjectList()).Execute();
            }
            else
            {
                projects = (new GetProjectListByUser()).Execute(ETLCredential.UserId);
            }

            if (projects != null)
            {
                // Convert to list
                foreach (ProjectModel projectModel in projects)
                {
                    listProject.Add(projectModel);
                } 
            }
            return PartialView("_ProjectDropDownListPartial", listProject);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ActionResult GetProjectPartialByUser(string userId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;

            // Get project list by userId
            var selectedProjectId = (new GetSelectedProject()).Execute(ETLCredential.UserId);

            if (selectedProjectId.HasValue)
            {
                // Set selected project to session
                (new SetSessionData()).Execute(Constants.SessionVars.CurrentProjectId, selectedProjectId.ToString());
            }

            // Get all projects of this user, including selected project if it's existing
            //var allProjectsOfThisUser = (new GetProjectListByUser()).Execute(ETLCredential.UserId, selectedProjectId);
            var allProjectsOfThisUser = (new GetProjectListByUser()).Execute(userId, selectedProjectId);

            return PartialView("_ProjectDropDownListPartial", allProjectsOfThisUser);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult GetLastProject()
        {
            try
            {
                // check authenticated status
                if (!WebSecurity.IsAuthenticated) return null;

                // Check roles
                if (Roles.IsUserInRole(Constants.RoleName.Admin)) return PartialView("_ProjectDropDownListPartial", null);

                var task = (new GetLastestProjectTask()).Execute(ETLCredential.UserId);

                // Get project list by userId
                var selectedProjectId = task.ProjectId;

                // Get all projects of this user, including selected project if it's existing
                var allProjectsOfThisUser = (new GetProjectListByUser()).Execute(ETLCredential.UserId, selectedProjectId);

                return PartialView("_ProjectDropDownListPartial", allProjectsOfThisUser);
            }
            catch (Exception ex)
            {
                return PartialView("_ProjectDropDownListPartial", null);
                throw;
            }

        }


        /// <summary>
        /// Return a partial view of category grid
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        /**
        public ActionResult GetLastCategory()
        {
            try
            {
                // check authenticated status
                if (!WebSecurity.IsAuthenticated) return null;

                // Check roles
                if (Roles.IsUserInRole(Constants.RoleName.Admin)) return PartialView("_CategoryGridPartial", null);

                // Find last category
                var task = (new GetLastestProjectTask()).Execute(ETLCredential.UserId);

                if (task.ProjectId.HasValue)
                {
                    // Get project item / check roles
                    var project = (new GetProjectById()).Execute(task.ProjectId);
                    //if (project.ProjectSuspended != true && !Roles.IsUserInRole(Constants.RoleName.Admin))
                    if (project.ProjectStatus == "SUSPENDED" && !Roles.IsUserInRole(Constants.RoleName.Admin))
                    {
                        // Save current category to session
                        //(new SetSessionCategory()).Execute(task.CategoryId.ToString());

                        // Get category list
                        //var categoryList = (new GetProjectCategoryToList()).Execute(task.ProjectId);
                        //return PartialView("_CategoryGridPartial", categoryList);
                    }
                    else
                    {
                        ViewBag.SuspendedAlert = "This project has been suspended. You cannot log onto it at the moment";
                        return PartialView("_CategoryGridPartial", null);
                    }
                }
                else
                {
                    ViewBag.SuspendedAlert = "Cannot find project id, please check it again";
                    return PartialView("_CategoryGridPartial", null);
                }
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return PartialView("_CategoryGridPartial", null);
                throw;
            }

        }
        **/

        /// <summary>
        /// Return a partial view of category grid
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult GetLastTask()
        {
            try
            {
                // check authenticated status
                if (!WebSecurity.IsAuthenticated) return null;

                // Check roles
                if (Roles.IsUserInRole(Constants.RoleName.Admin)) return PartialView("_TaskGridPartial", null);

                var task = (new GetLastestProjectTask()).Execute(ETLCredential.UserId);

                //if (task.CategoryId.HasValue)
                //{
                    // Get project item
                //    var tasks = (new GetProjectTaskToList()).Execute(task.ProjectId, task.CategoryId);
                      var tasks = (new GetProjectTaskToList()).Execute(task.ProjectId);
                      if (tasks != null)
                    {
                        return PartialView("_TaskGridPartial", tasks);
                    }
                    else
                    {
                        ViewBag.SuspendedAlert = "This project has been suspended. You cannot log onto it at the moment";
                        return PartialView("_TaskGridPartial", null);
                    }
                //}
                //else
                //{
                //    ViewBag.SuspendedAlert = "Cannot find project id, please check it again";
                //    return PartialView("_TaskGridPartial", null);
                //}
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return PartialView("_TaskGridPartial", null);

            }

        }

        /// <summary>
        /// Return a partial view of category grid
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public string GetLastProjectDetail()
        {
            try
            {
                // check authenticated status
                if (!WebSecurity.IsAuthenticated) return null;

                // Check roles
                if (Roles.IsUserInRole(Constants.RoleName.Admin)) return string.Empty;

                var task = (new GetLastestProjectTask()).Execute(ETLCredential.UserId);
                var result = string.Empty;

                if (task.ProjectId.HasValue)
                {
                    var currentProject = (new GetProjectById()).Execute(task.ProjectId.Value);
                    if (currentProject != null)
                    {
                        result += ETLCredential.UserFullName + "#";
                        //result += currentProject.ProjectLeadEnginner + "#";
                        result += String.Format("{0:MMM/dd/yyyy}", currentProject.ProjectStartDate) + "#";
                        result += String.Format("{0:MMM/M/yyyy}", currentProject.ProjectEndDate) + "#";
                        result += currentProject.ProjectStatus + "#";
                        //result += currentProject.ProjectCompleted + "#";
                        //result += currentProject.ProjectSuspended + "#";
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return string.Empty;
                throw;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult GetOtherEngineers(int? projectId)
        {
            try
            {
                // check authenticated status
                if (!WebSecurity.IsAuthenticated) return null;

                // Check roles
                if (Roles.IsUserInRole(Constants.RoleName.Admin)) return PartialView("_OtherEngineersPartial", null);

                if (projectId != null)
                {
                    var otherEngineers = (new GetOtherEngineers()).
                        Execute(projectId, ETLCredential.UserId);

                    return PartialView("_OtherEngineersPartial", otherEngineers);
                }
                else
                {
                    return PartialView("_OtherEngineersPartial", null);
                }
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return PartialView("_OtherEngineersPartial", null);
            }

        }

        public ActionResult GetLastOtherEngineers()
        {
            try
            {
                // check authenticated status
                if (!WebSecurity.IsAuthenticated) return null;

                // Check roles
                if (Roles.IsUserInRole(Constants.RoleName.Admin)) return PartialView("_OtherEngineersPartial", null);

                // Get other engineers
                var task = (new GetLastestProjectTask()).Execute(ETLCredential.UserId);
                if (task != null)
                {
                    var otherEngineers = (new GetOtherEngineers()).
                        Execute(task.ProjectId, ETLCredential.UserId);

                    return PartialView("_OtherEngineersPartial", otherEngineers);
                }
                else
                {
                    return PartialView("_OtherEngineersPartial", null);
                }
            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return PartialView("_OtherEngineersPartial", null);
                throw;
            }


        }

        public string CheckLogOnStatus()
        {
            try
            {
                // check authenticated status
                if (!WebSecurity.IsAuthenticated) return string.Empty;

                // Get current data
                var s = (new GetSessionDataModel()).Current();

                if(WebSecurity.IsAuthenticated)
                {
                    var checkClockOnStatus = (new CheckClockOnStatus()).Execute(ETLCredential.UserId);
                    if (!checkClockOnStatus)
                    {
                        return "You are not clocked onto an activity.Please clock onto an activity as soon as possible.";
                    }
                    else return string.Empty;
                }
                else
                {
                    return string.Empty;
                }

            }
            catch (Exception ex)
            {
                LogService.Service.Error(ex);
                return string.Empty;
                throw;
            }

        }
    }
}
